package com.beiye.drivertransport.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.frame.adapter.CommonAdapter;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.DataStatisticsActivity;
import com.beiye.drivertransport.SubActivity.EnterpriseAuditActivity;
import com.beiye.drivertransport.SubActivity.IllegalLearningActivity;
import com.beiye.drivertransport.SubActivity.OnlineEducationActivity;
import com.beiye.drivertransport.SubActivity.SubBusinessManagemenSafeLearnActivity;
import com.beiye.drivertransport.SubActivity.SubCompanyLearnActivity;
import com.beiye.drivertransport.SubActivity.SubLearnRecordActivity;
import com.beiye.drivertransport.accident.training.AccidentTrainingActivity;
import com.beiye.drivertransport.bean.AppModule;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.bean.UserBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.fragment.HomeFgt;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.prejobtraining.SubPreJobTrainingActivity;
import com.beiye.drivertransport.safelearn.SpecifiedLearningHomeActivity;
import com.beiye.drivertransport.utils.CameraCanUseUtils;
import com.beiye.drivertransport.utils.FileUtil;
import com.beiye.drivertransport.utils.HelpUtil;
import com.beiye.drivertransport.utils.ImageUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.TakePhotoDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.beiye.drivertransport.view.ShowGridView;
import com.githang.statusbar.StatusBarCompat;
import com.squareup.picasso.Picasso;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ModuleListActivity extends TwoBaseAty {

    TextView textView;
    ImageView imgCourseback;
    ShowGridView learnGv;

    private String adId;
    private String orgId;
    private String orgName;
    private Integer userMark;
    private Integer eeMark;
    private String photoUrl="";
    private String userId="E7DDE4D3-6CF5-DFBB-2275-F86A06DA7589";
    private LoginUserBean userInfo;
    private String contactPhone = "023-86058530";
    private File tempFile;

    private static final int GET_MODULE_LIST=1;//获取模块信息
    private static final int GET_ALL_USERINFO=2;//获取用户所有信息（包含企业信息）
    private static final int GET_USERINFO=3;//获取用户信息
    
    private static final int REQUEST_CAPTURE = 100;    //请求相机
    private static final int REQUEST_PICK = 101; //请求相册
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;//请求访问外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;//请求写入外部存储

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();

    private MaintAdapter maintAdapter;
    private ArrayList<AppModule.RowsBean> moduleTypeOneList = new ArrayList<>();
    private List<LoginUserBean.DataBean.CurUserOrgBean> orgList=new ArrayList<>();
    private LoginUserBean.DataBean.CurUserOrgBean orgInfo;


    @Override
    public int getLayoutId() {
        return R.layout.activity_module_list;
    }

    @Override
    public void initData() {
        textView = (TextView) findViewById(R.id.textView);
        imgCourseback = (ImageView) findViewById(R.id.img_Courseback);
        learnGv = (ShowGridView) findViewById(R.id.learn_gv);

        String result="{\n" +
                "    \"result\": true,\n" +
                "    \"data\": {\n" +
                "        \"lastLoginDate\": null,\n" +
                "        \"userName\": \"刘学章\",\n" +
                "        \"userId\": \"E7DDE4D3-6CF5-DFBB-2275-F86A06DA7589\"\n" +
                "    },\n" +
                "    \"msg\": \"操作成功\",\n" +
                "    \"rows\": null,\n" +
                "    \"total\": null,\n" +
                "    \"code\": 0\n" +
                "}";
        LoginUserBean loginUserBean = JSON.parseObject(result, LoginUserBean.class);
        UserManger.setUserInfo(loginUserBean);//保存用户信息

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));

        learnGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                SharedPreferences sp = getSharedPreferences("homefgt", Context.MODE_PRIVATE);

                int orgMark = orgInfo.getOrgMark();
                int minPer = orgInfo.getMinPer();
                int readInterval = orgInfo.getReadInterval();
                int signMark = orgInfo.gettSignMark();
                int Mark = orgInfo.getMark();
                String forbidHour = orgInfo.getForbidHour();
                int photoMark = orgInfo.gettPhotoMark();
                int mtPhotoNo = orgInfo.getMtPhotoNo();
                int faceRecgMark = orgInfo.getFaceRecgMark();
                int feeType = orgInfo.getFeeType();
                int mtSeqMark = orgInfo.getMtSeqMark();
                int allowMuT = orgInfo.getAllowMuT();
                int pjtMinPer = orgInfo.getPjtMinPer();
                int ftId = orgInfo.getFtId();
                String channelId = orgInfo.getChannelId();
                int uoSn=orgInfo.getUoSn();


                if (Utils.isFastClicker()) { //快速点击判断
                    return;
                }
                
                boolean orgStatus = orgStatus(orgMark, orgName); //企业状态判断
                if (!orgStatus) {
                    return;
                }

                int moduleId = maintAdapter.getItem(position).getModuleId();

                Bundle bundle = new Bundle();
                bundle.putInt("minPer", minPer);
                bundle.putInt("readInterval", readInterval);
                bundle.putInt("signMark", signMark);
                bundle.putInt("Mark", Mark);
                bundle.putString("orgId", orgId);
                bundle.putString("forbidHour", forbidHour);
                bundle.putInt("photoMark", photoMark);
                bundle.putInt("faceRecgMark", faceRecgMark);
                bundle.putInt("feeType", feeType);
                bundle.putString("orgName", orgName);
                bundle.putInt("mtSeqMark", mtSeqMark);
                bundle.putInt("allowMuT", allowMuT);
                bundle.putInt("pjtMinPer", pjtMinPer);
                bundle.putInt("ftId", ftId);
                bundle.putString("adId", adId);
                bundle.putString("channelId", channelId);
                bundle.putString("jumpType", "homeFgt");

                SharedPreferences sharedPreferences = getSharedPreferences("StaticData", Context.MODE_PRIVATE);
                SharedPreferences.Editor spEditor = sharedPreferences.edit();
                spEditor.putString("adId", adId);
                spEditor.putInt("uoSn", uoSn);
                spEditor.putString("orgId", orgId);
                spEditor.putInt("faceRecgMark", faceRecgMark);
                spEditor.putString("personphotoUrl", photoUrl);
                spEditor.putInt("mtPhotoNo", mtPhotoNo);
                spEditor.putString("orgName", orgName);
                spEditor.commit();

                if (photoUrl==null || TextUtils.isEmpty(photoUrl)) {
                    showTakePhotoPopupWindow();
                    return;
                }

                switch (moduleId) {
                    case 20100001://从业人员日常培训
                        if (eeMark != 1) {
                            HelpUtil.showTiShiDialog(ModuleListActivity.this, "此功能仅供从业人员使用");
                            return;
                        }
                        startActivity(SpecifiedLearningHomeActivity.class, bundle);
                        break;
                    case 20100002://学习记录
                        startActivity(SubLearnRecordActivity.class, bundle);
                        break;
                    case 20100003://岗前培训
                        if (eeMark != 1) {
                            HelpUtil.showTiShiDialog(ModuleListActivity.this, "此功能仅供从业人员使用");
                            return;
                        }
                        startActivity(SubPreJobTrainingActivity.class, bundle);
                        break;
                    case 20100004://在线测试
                        startActivity(OnlineEducationActivity.class, bundle);
                        break;
                    case 20100005://学习统计
                        startActivity(DataStatisticsActivity.class, bundle);
                        break;
                    case 20100006://企业管理员安全学习
                        startActivity(SubBusinessManagemenSafeLearnActivity.class, bundle);
                        break;
                    case 20100007://单位人员安全学习
                        startActivity(SubCompanyLearnActivity.class, bundle);
                        break;
                    case 20100008://审核学习
                        startActivity(EnterpriseAuditActivity.class, bundle);
                        break;
                    case 20100009://违章学习
                        startActivity(IllegalLearningActivity.class, bundle);
                        break;
                    case 20100012://事故培训
                        startActivity(AccidentTrainingActivity.class, bundle);
                        break;
                }
            }
        });
    }

    @Override
    public void requestData() {
        usefacephoto();
        allUserInfo();
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        super.onSuccess(result, call, response, what);
        if(what==GET_MODULE_LIST){
            AppModule appModule = JSON.parseObject(result, AppModule.class);
            List<AppModule.RowsBean> rows = appModule.getRows();
            moduleTypeOneList.clear();
            for (int i = 0; i < rows.size(); i++) {
                if (rows.get(i).getModuleType() == 1 && rows.get(i).getModuleId()!=20100011) {
                    moduleTypeOneList.add(rows.get(i));
                }
            }
            maintAdapter = new MaintAdapter(ModuleListActivity.this, moduleTypeOneList, R.layout.main_gridview_item);
            learnGv.setAdapter(maintAdapter);
        }else if(what==GET_ALL_USERINFO){
            UserBean userBean = JSON.parseObject(result, UserBean.class);
            orgList = userBean.getRows();
            orgInfo=orgList.get(6);

            userMark=orgInfo.getUserMark();
            orgId = orgInfo.getOrgId();
            orgName = orgInfo.getOrgName();
            adId = orgInfo.getAdId();
            eeMark = orgInfo.getEeMark();

            appModule(0,1);
        } else if(what==GET_USERINFO){
            MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
            MineUseBean.DataBean data = mineUseBean.getData();
            photoUrl=data.getPhotoUrl();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = Uri.fromFile(tempFile);
                    String cropImagePath = FileUtil.getRealFilePathFromUri(ModuleListActivity.this, uri);
                    File file = new File(cropImagePath);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    String userId = data.getUserId();
                    try {
                        FileInputStream fis = new FileInputStream(file);
                        Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                        bitmapByUrl = ImageUtil.compressScale(bitmapByUrl);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmapByUrl.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadImg(file, userId);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {

                    }
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = intent.getData();
                    String cropImagePath = FileUtil.getRealFilePathFromUri(ModuleListActivity.this, uri);
                    File file = new File(cropImagePath);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    String userId = data.getUserId();
                    try {
                        FileInputStream fis = new FileInputStream(file);
                        Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                        bitmapByUrl = ImageUtil.compressScale(bitmapByUrl);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmapByUrl.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadImg(file, userId);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {

                    }
                }
                break;
        }
    }


    public void onClick(View view) {
        finish();
    }

    /*
    适配器*/
    public class MaintAdapter extends CommonAdapter<AppModule.RowsBean> {
        private final List<AppModule.RowsBean> mList;
        private Context context;
        // 标记用户当前选择
        private int index = -1;

        public MaintAdapter(Context context, List<AppModule.RowsBean> mList, int itemLayoutId) {
            super(context, mList, itemLayoutId);
            this.context = context;
            this.mList = mList;
        }
        @Override
        public void convert(com.android.frame.adapter.ViewHolder holder, AppModule.RowsBean item, final int position) {
            ImageView img_gv = holder.getView(R.id.img_main);
            TextView tv_main = holder.getView(R.id.tv_main);

            String url = mList.get(position).getIconUrl();
            String moduleName = mList.get(position).getModuleName();
            tv_main.setText(moduleName);
            if (url != null) {
                Picasso.with(mContext).load(Uri.parse(url)).placeholder(R.mipmap.nophoto).into(img_gv);
            }
        }
    }

    /*
    自定义方法*/
    //企业状态
    private boolean orgStatus(int orgMark, String orgName) {
        boolean orgStatusUseAble = false;
        if (orgMark == 0) {
            HelpUtil.showTiShiDialog(ModuleListActivity.this, "您所在的企业" + orgName + "是无效状态，请联系管理员或者平台管理员（" + contactPhone + "）");
        } else if (orgMark == 2) {
            HelpUtil.showTiShiDialog(ModuleListActivity.this, "您所在的企业" + orgName + "是待审核状态，请联系管理员或者平台管理员（" + contactPhone + "）");
        } else if (orgMark == 3) {
            HelpUtil.showTiShiDialog(ModuleListActivity.this, "您所在的企业" + orgName + "还未审核通过，请联系管理员或者平台管理员（" + contactPhone + "）");
        } else if (orgMark == 4) {
            HelpUtil.showTiShiDialog(ModuleListActivity.this, "您" + orgName + "企业“余额”或者“学时”不足，请联系企业管理员或者平台管理员（" + contactPhone + "）");
        } else {
            orgStatusUseAble = true;
        }
        return orgStatusUseAble;
    }
    //个人头像弹窗
    private void showTakePhotoPopupWindow() {
        TakePhotoDialog.Builder builder = new TakePhotoDialog.Builder(ModuleListActivity.this);
        builder.setTitle("为方便后台管理员审核您的日常培训");
        builder.setMessage("请上传您的个人照片");
        builder.setPositiveButton("从手机中选择照片", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //权限判断
                if (ContextCompat.checkSelfPermission(ModuleListActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请READ_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(ModuleListActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到相册
                    gotoPhoto();
                }
                dialog.dismiss();
                //设置您的操作事项
            }
        });
        builder.setPositiveButton1("拍摄照片", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //权限判断
                if (ContextCompat.checkSelfPermission(ModuleListActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(ModuleListActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到调用系统相机
                    if (!CameraCanUseUtils.isCameraCanUse()) {
                        ToastUtil.showShortToast(ModuleListActivity.this, "请到手机设置界面里找驾运宝允许开启照相");
                        return;
                    }
                    gotoCamera();
                }
                dialog.dismiss();
                //设置您的操作事项
            }
        });
        builder.setNegativeButton("跳过", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //设置您的操作事项
            }
        });
        builder.create().show();
    }
    //打开相册
    private void gotoPhoto() {
        Log.d("evan", "*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }
    //打开相机
    private void gotoCamera() {
        Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(FileUtil.checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");

        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(ModuleListActivity.this, com.beiye.drivertransport.BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /*
    网络请求*/
    //根据企业或者行政规划获取动态模块
    private void appModule(int userMark,int eeMark) {
        new Login().getAppModule(adId, userMark, eeMark, this, GET_MODULE_LIST);
    }
    //获取用户信息
    private void usefacephoto() {
        new Login().getUser(userId, this, GET_USERINFO);
    }
    //获取用户所有信息
    private void allUserInfo(){
        new Login().getUseData(userId, 1, this, GET_ALL_USERINFO);
    }

    //上传头像
    private void uploadImg(File mediaFile, String userId) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (mediaFile != null) {
            builder.addFormDataPart("headPhoto", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("userId", userId);
        }
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "wx/uploadOfHeadPhoto")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                String data = upPhotoBean.getData();
                Looper.prepare();
                usefacephoto(); //人脸识别要求上传头像和签名
                Looper.loop();
                LogUtils.e("上传图片", data);
            }
        });
    }
}
